package com.xiongwei.io;

import com.xiongwei.pojo.User;
import jdk.swing.interop.SwingInterOpUtils;

import java.io.*;
import java.util.Arrays;

/**
 * 可序列化的java对象必须实现java.io.Serializable接口,类似Serializable这样的空接口被称为"标记接口"
 *
 * 反序列化时不调用构造方法,可设置serializableUID作为版本号(非必须)
 *
 * Java的序列化机制仅适用于java,如果需要与其他语言交换数据,必须使用通用的序列化方法,例如JSON
 *
 * @author XiongWei
 * @date 2021/1/11
 */
public class SerializableUse {

    /**
     * java对象--->byte[] 序列化
     * byte[]--->java对象 反序列化
     * @param args
     */
    public static void main(String[] args) {
        SerializableUse su = new SerializableUse();
        //su.javaObjectToByteArray();
        su.byteArrayToJavaObject();
    }

    //把一个Java对象变为byte[],需要使用ObjectOutputStream,它负责把一个java对象写入一个字节流
    public void javaObjectToByteArray() {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try(ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream)) {
            oos.writeInt(123);
            oos.writeUTF("hello");
            oos.writeObject(new User("xw", 99));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray()));
    }

    public void byteArrayToJavaObject() {
        byte[] bb = {-84, -19, 0, 5, 119, 11, 0, 0, 0, 123, 0, 5, 104, 101, 108, 108, 111, 115, 114, 0, 22, 99, 111, 109, 46, 120, 105, 111, 110, 103, 119, 101, 105, 46, 112, 111, 106, 111, 46, 85, 115, 101, 114, 33, 79, 20, 64, 65, -109, -14, 114, 2, 0, 2, 73, 0, 5, 115, 99, 111, 114, 101, 76, 0, 4, 110, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 120, 112, 0, 0, 0, 99, 116, 0, 2, 120, 119};
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bb);

        try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            int i = objectInputStream.readInt();
            String s = objectInputStream.readUTF();
            User u = (User)objectInputStream.readObject();
            System.out.println(i);
            System.out.println(s);
            System.out.println(u);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
